//
//  SDDetectionReportVC.m
//  skinDetection
//
//  Created by  liangzhun on 2018/11/2.
//  Copyright © 2018年  liangzhun. All rights reserved.
//

#import "SDDetectionReportVC.h"
#import "SDDetectionDataModel.h"
#import "SDDetectionReportCell.h"
#import "SDShareReportVC.h"
#import "SDSkinAnalysisCell3.h"
#import "SDDetectionReportCell2.h"
#import "SDShowSkinImageController.h"
#import "SDDetectionReportHeaderView.h"
#import "SDdetectionReportFooterView.h"

#import "SDDetectionReportData.h"
#import "SDDetectionReportModel.h"

#import "SDProductRecommendVC.h"

static NSString *const cellIden = @"SDDetectionReportCell";
static NSString *const cellIden1 = @"SDSkinAnalysisCell3";
static NSString *const cellIden2 = @"SDDetectionReportCell2";
static NSString *const headerIden = @"SDDetectionReportHeaderView";
static NSString *const footerIden = @"SDdetectionReportFooterView";
@interface SDDetectionReportVC ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property (nonatomic ,assign)NSInteger selectType;//设置选择的皮肤类型 默认选择干纹
@property (nonatomic ,strong)NSArray *contentArray;
@property (nonatomic ,strong)NSArray *skinTitleArray;

@property (nonatomic ,strong)SDShareReportVC *shareVC;

@property(nonatomic ,strong) SDDetectionReportModel *showModel;

@property(nonatomic ,strong) NSTimer *timer;

@property(nonatomic ,strong) UILabel *labSorce;

@property(nonatomic ,assign) double sorce;
@end

@implementation SDDetectionReportVC
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (!self.isFromReportList) {
        if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        }
    }
    
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (!self.isFromReportList) {
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.selectType = 1;
    
    [self.navView setBackgroundColor:RGBA(255, 255, 255, 0.0)];
    [self loadData];
    
    _navHeight.constant = SDNavBar_Height;
    
    self.tableView.estimatedRowHeight = 0;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    
     [self.tableView registerNib:[UINib nibWithNibName:cellIden bundle:nil] forCellReuseIdentifier:cellIden];
    
     [self.tableView registerNib:[UINib nibWithNibName:cellIden1 bundle:nil] forCellReuseIdentifier:cellIden1];
    
     [self.tableView registerNib:[UINib nibWithNibName:cellIden2 bundle:nil] forCellReuseIdentifier:cellIden2];
    
    [self.tableView registerNib:[UINib nibWithNibName:headerIden bundle:nil] forHeaderFooterViewReuseIdentifier:headerIden];
    
    [self.tableView registerNib:[UINib nibWithNibName:footerIden bundle:nil] forHeaderFooterViewReuseIdentifier:footerIden];
    
    [self.view addSubview:self.shareVC.view];
    [self addChildViewController:self.shareVC];
    
    
}
- (void)loadData
{
    [SDNetwork getReportinfoWithReportId:self.reportId Finish:^(NSDictionary * _Nullable dic, NSError * _Nullable error) {
        
        if (!error) {
            self.showModel = [SDDetectionReportModel modelObjectWithDictionary:dic];
            self.contentArray = self.showModel.data.resImg1List;
            self.shareVC.reportId = [NSString stringWithFormat:@"%d",self.reportId];
            [self.tableView reloadData];
            self.sorce = 0.0;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(changeSorce) userInfo:nil repeats:YES];
        }
        
    }];
    
}

/**
 分数跳动动画
 */
- (void)changeSorce
{
    self.sorce = self.sorce + self.showModel.data.score/20.00;
    if (self.sorce >= self.showModel.data.score)
    {
        self.sorce = self.showModel.data.score;
        [self.timer invalidate];
        self.timer = nil;
    }
    NSMutableAttributedString *attSorce = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.f分",self.sorce]];
    [attSorce addAttribute:NSFontAttributeName value:Font(31) range:NSMakeRange(0, attSorce.length - 1)];
    self.labSorce.attributedText = attSorce;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
   if (indexPath.section == 0){
        
        SDDetectionReportCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIden];
       [self.skinTitleArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           
           NSDictionary *dic = obj;
           UIButton *btn = cell.btnArray[idx];
           btn.tag = idx + 1;
           [btn setTitle:[dic objectForKey:@"title"] forState:UIControlStateNormal];
           [btn addTarget:self action:@selector(showSkin:) forControlEvents:UIControlEventTouchUpInside];
           
       }];
       
        return cell;
        
    }else{

        SDDetectionReportCell2 *cell = [tableView dequeueReusableCellWithIdentifier:cellIden2];
        
        cell.showModel = self.showModel;
        cell.selectType = self.selectType;
        cell.block = ^(NSInteger select) {
        self.selectType = select;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                [self.tableView reloadData];
            });
            
            
        };
        return cell;

    }
    
    
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return indexPath.section == 0? 290:267;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.section == 0? 290:[self getAllHeight];

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0? 195 - 64 + SDNavBar_Height:0.001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return section == 0? 0.001:145;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
     SDDetectionReportHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIden];
        headerView.topHeight.constant = 130 - 64 + SDNavBar_Height;
        self.labSorce = headerView.sorceLab;
        headerView.data = self.showModel.data;
        [headerView addLayer];
        return headerView;
        
        
    }
    
    return nil;
   
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        
        return nil;
        SDdetectionReportFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:footerIden];
        SDDetectionReportData *data = self.showModel.data;
        [footerView.bgView.layer setCornerRadius:3];
        [footerView.bgView.layer setMasksToBounds:YES];
        [footerView.skinTypeBtnArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UIButton *skinBtn = obj;
            skinBtn.tag = idx + 1;
            [skinBtn setTitleColor:SDMainTextColor forState:UIControlStateNormal];
            
            if (self.selectType == idx + 1)
            {
               footerView.selectedBtn = skinBtn;
               footerView.moveView.center = skinBtn.center;
               [skinBtn setTitleColor:SDWhiteColor forState:UIControlStateNormal];
                
            }
            
            [skinBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
                if (footerView.selectedBtn != skinBtn) {
                    
                    //footerView.moveView.center = skinBtn.center;
                    footerView.selectedBtn = skinBtn;
                    self.selectType = skinBtn.tag;
                    [footerView.selectedBtn setTitleColor:SDMainTextColor forState:UIControlStateNormal];
                    self.contentArray = self.selectType == 1? data.resImg1List:self.selectType == 2? data.resImg2List:self.selectType == 3? data.resImg3List:self.selectType == 4? data.resImg4List:data.resImg5List;
                    
                    [UIView animateWithDuration:0.3 animations:^{
                        footerView.moveView.center = footerView.selectedBtn.center;
                    } completion:^(BOOL finished) {
                        
                         [skinBtn setTitleColor:SDWhiteColor forState:UIControlStateNormal];
                        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
                    }];
                    
                }
            }];
            
            
        }];
        
        return footerView;
        
    }else
    {
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SDMainScreenWidth, 145)];
        UIButton *recommendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [recommendBtn setFrame:CGRectMake(33, 50, SDMainScreenWidth - 66, 45)];
        [recommendBtn.titleLabel setFont:Font(17)];
        [recommendBtn setBackgroundColor:SDMainColor];
        recommendBtn.layer.cornerRadius = 5.f;
        recommendBtn.layer.masksToBounds = YES;
        [recommendBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
            
           // SDDetectionReportData *data = self.showModel.data;
            SDProductRecommendVC *vc = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDProductRecommendVC class])];
           // vc.type = self.selectType == 1? data.resImg1SubId:self.selectType == 2? data.resImg2SubId:self.selectType == 3? data.resImg3SubId:self.selectType == 4? data.resImg4SubId:data.resImg5SubId;
            vc.typeStr = [self getTypesStr];
            vc.isFromReport = YES;
            [self.navigationController pushViewController:vc animated:YES];
            
        }];
        [recommendBtn setTitle:@"产品推荐" forState:UIControlStateNormal];
        [footerView addSubview:recommendBtn];
        return footerView;
        
    }

    
}
- (NSString *)getTypesStr
{
    
    SDDetectionReportData *data = self.showModel.data;
    NSString *str = [NSString stringWithFormat:@"%.f,%.f,%.f,%.f,%.f",data.resImg1SubId,data.resImg2SubId,data.resImg3SubId,data.resImg4SubId,data.resImg5SubId];
    return str;
    
}
- (void)showSkin:(UIButton *)sender
{
    SDShowSkinImageController *vc = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDShowSkinImageController class])];
    vc.dic = self.skinTitleArray[sender.tag - 1];
    [vc.view setFrame:self.view.bounds];
    [self.view addSubview:vc.view];
    [self addChildViewController:vc];
    
}


- (IBAction)back:(UIButton *)sender {
    
    self.isFromReportList? [self.navigationController popViewControllerAnimated:YES]:[self.navigationController popToRootViewControllerAnimated:YES];;
    
}

- (IBAction)shareReport:(UIButton *)sender {
    
    [self.shareVC presentShareView];
    
}
- (CGFloat)getAllHeight
{
    CGFloat height = 0.0;
    for (int c = 0; c < self.contentArray.count; c++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:c+1];
        height = height + [self getReasonTextHeightWithIndexPath:indexPath];
    }
    return height + 210 + 57;
}
- (CGFloat)getReasonTextHeightWithIndexPath:(NSIndexPath *)indexPath
{
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    style.paragraphSpacingBefore = 5;
    
    NSString *seperate = @"     ";
    NSString *content = self.contentArray[indexPath.section - 1];
    content = indexPath.section ==2? [content stringByReplacingOccurrencesOfString:@"：" withString:seperate]:content;
    NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:content];
    [att addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, content.length)];
    
    UIColor *contentColor = indexPath.section == 3? SDMainColor:SDMainTextColor;
    [att addAttribute:NSForegroundColorAttributeName value:contentColor range:NSMakeRange(0, att.length)];
    if (indexPath.section == 2&&[content componentsSeparatedByString:seperate].count > 2) {
        
        NSString *firstTitle = [content componentsSeparatedByString:seperate].firstObject;
        
        [att addAttribute:NSForegroundColorAttributeName value:SDMainColor range:NSMakeRange(0, firstTitle.length)];
        NSString *second = [content componentsSeparatedByString:seperate][1];
        [att addAttribute:NSForegroundColorAttributeName value:SDMainColor range:NSMakeRange(second.length + seperate.length, firstTitle.length)];
        
    }else if(indexPath.section == 1&&[content containsString:@"："])
    {
        NSString *firstTitle = [content componentsSeparatedByString:@"。"].firstObject;
        
        [att addAttribute:NSForegroundColorAttributeName value:SDMainColor range:NSMakeRange(0, firstTitle.length)];
        
    }
    
    return [SDMethodTool getAttTextHeightWithText:att withTextFontSize:Font(15) Width:SDMainScreenWidth - 30] + 15;
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;
    
    [self.navView setBackgroundColor:RGBA(255, 255, 255, y/(130 - 64))];
}
-(NSArray *)skinTitleArray
{
    SDDetectionReportData *data = self.showModel.data;
   
    return self.showModel? @[@{@"image":data.resImg1,@"title":data.resImg1Desc},@{@"image":data.resImg2,@"title":data.resImg2Desc},@{@"image":data.resImg3,@"title":data.resImg3Desc},@{@"image":data.resImg4,@"title":data.resImg4Desc},@{@"image":data.resImg5,@"title":data.resImg5Desc}]:@[];
    
}

-(SDShareReportVC *)shareVC
{
    if (!_shareVC) {
        _shareVC = [SDMethodTool getViewControlWithIdentifier:NSStringFromClass([SDShareReportVC class])];
        //    vc.dic = self.skinTitleArray[sender.tag - 1];
        [_shareVC.view setFrame:self.view.bounds];
        
    }
    return _shareVC;
}
-(void)setSelectType:(NSInteger)selectType
{
    _selectType = selectType;
    SDDetectionReportData *data = self.showModel.data;
    self.contentArray = self.selectType == 1? data.resImg1List:self.selectType == 2? data.resImg2List:self.selectType == 3? data.resImg3List:self.selectType == 4? data.resImg4List:data.resImg5List;


}
@end
